<?php
/**
 * MKFilelogRoute class file
 *
 * @author ZhangJinlong <zhangjinlong@pwrd.com>
 * @link http://www.mk-style.com/
 * @copyright Copyright &copy; 2012 C&C Media
 */

class FilelogRoute extends CLogRoute
{
    /**
     * 日志保存路径
     * @var string
     */
    private $_path;

    /**
     * 日志名称前缀
     * @var string
     */
    private $_prefix = '';

    /**
     * 文件权限
     * @var integer
     */
    private $_filePermission = 0755;

    /**
     * (non-PHPdoc)
     * @see CLogRoute::init()
     */
    public function init()
    {
        parent::init();

        if (!$this->_path)
        {
            $this->_path = Yii::getPathOfAlias('application.runtime.log');
        }

        $this->_path = rtrim($this->_path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.date('Y-m');

        if (is_dir($this->_path) === FALSE)
        {
            @mkdir($this->_path, $this->_filePermission, TRUE);
        }
    }

    /**
     * 获得日志保存路径
     * @return string
     */
    public function getPath()
    {
        return $this->_path;
    }

    /**
     * 设置日志保存路径
     * @param string $value
     */
    public function setPath($path)
    {
        $this->_path = $path;
    }

    /**
     * 获得日志文件名称前缀
     * @return string
     */
    public function getPrefix()
    {
        return $this->_prefix;
    }

    /**
     * 设置日志文件名称前缀
     * @param string $prefix
     */
    public function setPrefix($prefix)
    {
        $this->_prefix = $prefix;
    }

    /**
     * (non-PHPdoc)
     * @see CLogRoute::processLogs()
     */
    public function processLogs($logs)
    {
        $logList = array();

        foreach ($logs as $log)
        {
            $logList[$log['1']][] = $log;
        }

        foreach ($logList as $key => $logs)
        {
            $handle = fopen($this->_path.DIRECTORY_SEPARATOR.$this->_prefix.$key.'_'.date('Ymd').'.log', 'a');

            if (flock($handle, LOCK_EX) !== FALSE)
            {
                foreach ($logs as $log)
                {
                    fwrite($handle, $this->formatLogMessage($log[0], $log[1], $log[2], $log[3]));
                }

                flock($handle, LOCK_UN);
            }

            fclose($handle);
        }
    }
}